package com.lw.leetcode.tree.b;

import com.lw.leetcode.tree.TreeNode;

/**
 * 1315. 祖父节点值为偶数的节点和
 *
 * @Author liw
 * @Date 2021/5/20 17:20
 * @Version 1.0
 */
public class SumEvenGrandparent {

    private int sum = 0;

    public int sumEvenGrandparent(TreeNode root) {
        find(root);
        return sum;
    }

    private void find(TreeNode root) {
        if (root == null) {
            return;
        }
        if ((root.val & 1) != 1) {
            int n = 0;
            TreeNode item;
            TreeNode t = root.left;
            if (t != null) {
                item = t.left;
                if (item != null) {
                    n += item.val;
                }
                item = t.right;
                if (item != null) {
                    n += item.val;
                }
            }
            t = root.right;
            if (t != null) {
                item = t.left;
                if (item != null) {
                    n += item.val;
                }
                item = t.right;
                if (item != null) {
                    n += item.val;
                }
            }
            sum += n;
        }
        find(root.left);
        find(root.right);
    }

}
